import re


from rest_framework import serializers
from rest_framework_jwt.settings import api_settings
from django_redis import get_redis_connection
from goods.models import SKU
from users.models import User, Address
from utils.setjwt import set_jwt

'''
1 read_only 是返回字段设置属性
2 write_only 是传过来的字段属性设置

'''


# 注册的序列化器
class RegisterUserSerializer(serializers.ModelSerializer):

    password2 = serializers.CharField(label='校验密码', allow_null=False, allow_blank=False, write_only=True)
    sms_code = serializers.CharField(label='短信验证码', max_length=6, min_length=6, allow_null=False, allow_blank=False,
                                     write_only=True)
    allow = serializers.CharField(label='是否同意协议', allow_null=False, allow_blank=False, write_only=True)

    token = serializers.CharField(label='登录状态token', read_only=True)  # 增加token字段

    class Meta:
        model = User
        fields = ('id', 'username', 'password', 'mobile', 'password2', 'sms_code', 'allow','token')
        # fields = '__all__'

        extra_kwargs = {
            'id': {'read_only': True},
            'username': {
                'min_length': 5,
                'max_length': 20,
                'error_messages': {
                    'min_length': '仅允许5-20个字符的用户名',
                    'max_length': '仅允许5-20个字符的用户名',
                }
            },
            'password': {
                'write_only': True,
                'min_length': 8,
                'max_length': 20,
                'error_messages': {
                    'min_length': '仅允许8-20个字符的密码',
                    'max_length': '仅允许8-20个字符的密码',
                }
            }
        }

    def validate_mobile(self, value):
        if not re.match(r'1[345789]\d{9}', value):
            raise serializers.ValidationError('手机号格式不正确')
        return value

    def validate_allow(self, value):
        # 注意,前段提交的是否同意,我们已经转换为字符串
        if value != 'true':
            raise serializers.ValidationError('您未同意协议')
        return value

    def validate(self, attrs):

        # 比较密码
        password = attrs.get('password')
        password2 = attrs.get('password2')

        if password != password2:
            raise serializers.ValidationError('密码不一致')
        # 比较手机验证码
        # 获取用户提交的验证码
        code = attrs['sms_code']
        # 获取redis中的验证码
        redis_conn = get_redis_connection('code')
        # 获取手机号码
        mobile = attrs['mobile']
        redis_code = redis_conn.get('sms_%s' % mobile)
        if redis_code is None:
            raise serializers.ValidationError('验证码过期')

        if redis_code.decode() != code:
            raise serializers.ValidationError('验证码不正确')

        return attrs

    # 从写添加数据的方法
    def create(self, validated_data):
        # 将模型中不存在的字段删除
        del validated_data['sms_code']
        del validated_data['password2']
        del validated_data['allow']

        user = User.objects.create(**validated_data)
        # 将密码修改为暗纹
        user.set_password(validated_data.get('password'))

        user.save()

        token = set_jwt(user)

        user.token = token

        return user


class PeopleTokenSerializer(serializers.ModelSerializer):

    class Meta:
        model = User
        fields = ['id','username','email','mobile','email_active']


class EmailAPIVIewSerializer(serializers.ModelSerializer):

    class Meta:
        model = User
        fields = ['email']
        extra_kwargs ={
            'email':{'required':True}
        }

'''
验证的字段　mobile

'''


class UserAdressAPIViewSerializer(serializers.ModelSerializer):
    # 序列化器使用的
    province = serializers.StringRelatedField(read_only=True)
    city = serializers.StringRelatedField(read_only=True)
    district = serializers.StringRelatedField(read_only=True)

    # 反序列化器使用
    province_id = serializers.IntegerField(required=True,label='省id')
    city_id = serializers.IntegerField(required=True,label='市id')
    district_id = serializers.IntegerField(required=True,label='区id')

    class Meta:
        model = Address
        # fields = ['mobile','province','city','district','place','title','receiver']
        exclude = ['user','is_deleted','create_time','update_time']

    def create(self, validated_data):
        user = self.context['user']
        validated_data['user'] = user
        address = Address.objects.create(**validated_data)

        # address.save()
        return address


class UserHestoryAPIViewSerializer(serializers.Serializer):
    """
       添加用户浏览记录序列化器
       """
    sku_id = serializers.IntegerField(label='商品编号', min_value=1, required=True)


    def validate_sku_id(self, value):
        """
        检查商品是否存在
        """
        try:
            SKU.objects.get(pk=value)

        except SKU.DoesNotExist:
            raise serializers.ValidationError('商品不存在')

        return value

    def create(self, validated_data):

        user = self.context.get('request').user
        sku_id = validated_data.get('suk_id')

        redis_conn = get_redis_connection('history')
        # 删除　重复字段
        redis_conn.lrem('history_%s'%user.id,0,sku_id)
        # 添加
        redis_conn.lpush('history_%s'%user.id,sku_id)

        # 保留前５个
        redis_conn.ltrim('history_%s'%user.id,0,4)

        return validated_data


class SKUSerializer(serializers.ModelSerializer):

    class Meta:
        model = SKU
        fields = ('id', 'name', 'price', 'default_image_url', 'comments')

    # def update(self, instance, validated_data):
    #
    #     user = instance.user
    #     id = self.context.get('id')
    #     try:
    #         user = Address.objects.get(id=id)
    #     except Address.DoseNotExist:
    #         serializers.ValidationError('查询错误')
    #
    #     default_address_web = User.objects.get(id =user.id)
    #     default_address_web['default_address'] = True
    #
    #     return instance
